#include "gameview.h"
#include "qevent.h"
#include "qpainter.h"
#include <sys/time.h>

GameView::GameView(QWidget *parent)
    : QWidget{parent}
{
    fc = new FcThread(this);
    fc->start();
    setFocusPolicy(Qt::StrongFocus);
    //    QStringList args = qApp->arguments();//返回命令行参数列表
    //    if(args.size() > 0)
    //    {
    //        for(int i=0;i<args.size();i++)
    //        {
    //            QString cmd = args.at(i);
    //            if(cmd.endsWith(".nes"))
    //            {
    //                fc->SyncLoadRom(cmd);
    //                break;
    //            }
    //        }
    //    }
}

inline uint64_t getTimeUs()
{
    timeval tv;
    gettimeofday(&tv, NULL);
    return (uint64_t)1000000 * tv.tv_sec + tv.tv_usec;
}

void GameView::paintEvent(QPaintEvent *paint)
{
    if (markTime == 0)
        markTime = getTimeUs();
    fc->GetFrameBuffer(screen, sizeof(screen));

    QPainter painter(this);
    QImage image((uchar *)pixels, 256, 240, QImage::Format_ARGB32);

    // QPixmap pix(256*240);
    // pix.loadFromData((char*)screen)
    fc->drawLock.lock();
    memcpy(pixels,screen,256*240*4);
    fc->drawLock.unlock();

    int width = this->width();
    int height = this->height();
    float scalex = (float)width / (256.f - 16);
    float scaley = (float)height / (240.f - 16);
    float scale = scalex > scaley ? scaley : scalex;

    int finewidth = (int)((256.f - 16) * scale);
    int fineheight = (int)((240.f - 16) * scale);
    int left = (width - finewidth) / 2;
    int top = (height - fineheight) / 2;
//    painter.setRenderHints(QPainter::Antialiasing);
//    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    painter.fillRect(QRectF(0, 0, width, height), Qt::GlobalColor::black);
    painter.drawImage(QRectF(left, top, finewidth, fineheight), image, QRectF(8, 8, 256 - 16, 240 - 16));
    QString s = "FPS:" + QString::number(drawFps);
    painter.setPen(Qt::white);
    // QFont qfont("宋体",15);
    QFont font("宋体", 15);
    font.setFamily(font.defaultFamily());
    painter.setFont(font);
    painter.drawText(this->x(), this->y(), s);
    framecount++;
    auto nowtime = getTimeUs();
    if (nowtime - markTime > 1000 * 1000)
    {
        drawFps = (double)framecount / (double)((nowtime - markTime) / 1000000.0);
        markTime = nowtime;
        framecount = 0;
        // qDebug("draw fps:%d\n",FPS);
    }
}

void GameView::keyPressEvent(QKeyEvent *event) // 键盘按下事件
{
    for (int i = 0; i < 8; i++)
    {
        if (event->key() == mKeyMap[i])
        {
            fc->Input(i, 1);
            return;
        }
    }
}
void GameView::keyReleaseEvent(QKeyEvent *event) // 键盘松开事件
{
    for (int i = 0; i < 8; i++)
    {
        if (event->key() == mKeyMap[i])
        {
            fc->Input(i, 0);
            return;
        }
    }
}

void GameView::SyncLoadRom(QString filename)
{
    fc->SyncLoadRom(filename);
}
